﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.Reflection;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;

namespace Jbe.Composite.Extensions
{
    /// <summary>
    /// Defines the base class for a model.
    /// </summary>
    public abstract class Model : INotifyPropertyChanged
    {
        /// <summary>
        /// Occurs when a property value changes.
        /// </summary>
        public event PropertyChangedEventHandler PropertyChanged;


        /// <summary>
        /// Raises the <see cref="E:PropertyChanged"/> event.
        /// </summary>
        /// <param name="e">The <see cref="System.ComponentModel.PropertyChangedEventArgs"/> instance containing the event data.</param>
        protected virtual void OnPropertyChanged(PropertyChangedEventArgs e)
        {
            if (PropertyChanged != null) { PropertyChanged(this, e); }
        }

        /// <summary>
        /// Raises the <see cref="E:PropertyChanged"/> event.
        /// </summary>
        /// <param name="propertyInfo">The property info of the property that has changed.</param>
        [SuppressMessage("Microsoft.Design", "CA1030:UseEventsWhereAppropriate")]
        protected void RaisePropertyChanged(PropertyInfo propertyInfo)
        {
            CheckPropertyInfo(propertyInfo);
            OnPropertyChanged(new PropertyChangedEventArgs(propertyInfo.Name));
        }

        protected void RaisePropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }


        [Conditional("DEBUG")]
        private void CheckPropertyInfo(PropertyInfo propertyInfo)
        {
            if (!propertyInfo.DeclaringType.IsInstanceOfType(this))
            {
                throw new ArgumentException("The passed propertyInfo is from the wrong DeclaringType.", "propertyInfo");
            }
        }
    }
}
